package com.spring;

import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class ZhnApplicationContext {
    private Class configClass;

    private ConcurrentHashMap<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>();
    private ConcurrentHashMap<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<String, BeanDefinition>();
    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();
    public ZhnApplicationContext(Class configClass){
        this.configClass = configClass;
        //解析配置类
        //ComponentScan注解---->扫描路径---->扫描---->BeanDefinition---->BeanDefinitionMap
        scan(configClass);
        for(String beanName:beanDefinitionMap.keySet()){
            BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
            if(beanDefinition.getScope().equals("singleton")){
                Object bean = createBean(beanName,beanDefinition);
                singletonObjects.put(beanName,bean);
            }
        }
    }

    private Object createBean(String beanName,BeanDefinition beanDefinition) {
        Class clazz = beanDefinition.getClazz();
        try {
            Object instance = clazz.getDeclaredConstructor().newInstance();
            // 依赖注入
            for(Field declaredField: clazz.getDeclaredFields()){
                if (declaredField.isAnnotationPresent(Autowired.class)) {
                    Object bean = getBean(declaredField.getName());
                    declaredField.setAccessible(true);
                    declaredField.set(instance,bean);
                }
            }
            //Aware回调
            if(instance instanceof BeanNameAware){
                ((BeanNameAware)instance).setBeanName(beanName);
            }

            //初始化前
            for(BeanPostProcessor beanPostProcessor: beanPostProcessorList){
                instance = beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
            }

            //初始化
            if(instance instanceof InitializingBean){
                try {
                    ((InitializingBean)instance).afterPropertiesSet();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            //扩展机制，后置处理器
            //初始化后
            for(BeanPostProcessor beanPostProcessor: beanPostProcessorList){
                instance = beanPostProcessor.postProcessAfterInitialization(instance, beanName);
            }


            return instance;

        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    private void scan(Class configClass) {
        ComponentScan componentScanAnnotation = (ComponentScan) configClass.getAnnotation(ComponentScan.class);
        String path = componentScanAnnotation.value();//扫描路径
        System.out.println(path);
        //扫描
        //类加载器: Bootstrap->jre/lib Ext->jre/ext/lib App->classPath 获取路径
        String newPath = path.replace(".", "/");
        ClassLoader classLoader = ZhnApplicationContext.class.getClassLoader();
        URL resource = classLoader.getResource(newPath);
        System.out.println(resource);
        File file = new File(resource.getFile());
        if(file.isDirectory()){
            File[] files = file.listFiles();
            for(File f: files){
                System.out.println(f);
                String name = f.getAbsolutePath();
                if(name.endsWith(".class")){
                    String sub = name.substring(name.indexOf("com"), name.indexOf(".class"));
                    String res = sub.replace("\\", ".");
                    System.out.println(res);
                    try {
                        Class<?> aClass = classLoader.loadClass(res);
                        if (aClass.isAnnotationPresent(Component.class)) {
                            //表示该类是一个Bean
                            // Class->Bean????  解析当前Bean是单例Bean，还是prototype的Bean
                            //引出BeanDefinition

                           if(BeanPostProcessor.class.isAssignableFrom(aClass)){
                               //class1.isAssignableFrom(class2) 判定此 Class 对象所表示的类或接口与指定的 Class 参数所表示的类或接口是否相同，或是否是其超类或超接口
                               BeanPostProcessor instance = (BeanPostProcessor) aClass.getDeclaredConstructor().newInstance();
                               beanPostProcessorList.add(instance);
                           }


                            Component componentAnnotation = aClass.getDeclaredAnnotation(Component.class);
                            String beanName = componentAnnotation.value();

                            BeanDefinition beanDefinition = new BeanDefinition(); //表示Bean的定义
                            beanDefinition.setClazz(aClass);
                            if(aClass.isAnnotationPresent(Scope.class)){
                                Scope scopeAnnotation = aClass.getDeclaredAnnotation(Scope.class);
                                String scopeValue = scopeAnnotation.value();
                                beanDefinition.setScope(scopeValue);
                            }else {
                                beanDefinition.setScope("singleton");
                            }
                            beanDefinitionMap.put(beanName,beanDefinition);
                        }
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        throw new RuntimeException(e);
                    } catch (InstantiationException e) {
                        throw new RuntimeException(e);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    } catch (NoSuchMethodException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }

    public Object getBean(String beanName){
        if(beanDefinitionMap.containsKey(beanName)){
            BeanDefinition beanDefinition =  beanDefinitionMap.get(beanName);
            if(beanDefinition.getScope().equals("singleton")){
                Object o = singletonObjects.get(beanName);
                return o;
            }else {
                //创建bean
                Object bean = createBean(beanName,beanDefinition);
                return bean;
            }
        }
        else {
            //不存在对应的Bean
            throw new NullPointerException();
        }
    }
}
